/* 
 * @Author: Havery 
 * @Date: 2020-11-12 14:00:31  
 * @function: axios 请求封装
 * ---------------------------------------------------------- 
 */
import axios from 'axios';
// import options from './config';
import router from '../router';
import store from '../store'
import {
  Message,
  Loading
} from 'element-ui'

/* 当页面有两个接口时，第一个接口loading的close事件会直接将第二个接口的loading实例也close */
let loadingInstance = null
let needLoadingRequestCount = 0
const http = {
  //axios 配置
  //param.modal 遮罩层 默认显示
  //param.baseURL 基本路径 默认store.state.config.devopsURI 
  //param.data//post/get请求参数 
  //param.auth
  httpRequest(param) {
    let userInfo = store.getters.userInfo;
    let curDateTime = new Date(); //当前时间
    if (curDateTime > userInfo.validTime && param.auth) {
      return new Promise(() => {
        Message.error({ message: '登录超时!', type: "warning", offset: 400 ,showClose:true});
        router.push({ path: "/" });
      });
    } else {
      //遮罩层
      param.modal = (param.modal === false ? false : true);
      param.baseURL = param.baseURL != undefined ? param.baseURL : store.getters.devopsURI;
      param.data == param.data != undefined ? param.data : {};
      const serivce = axios.create({
        baseURL: param.baseURL, //请求基地址
        timeout: 20000, //请求超时时长
        headers: {
          'Content-Type': 'application/json;charset=utf-8'
        }
        //headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
      });
      //请求拦截
      serivce.interceptors.request.use(
        (config) => {
          if (param.modal) {
            http.showFullScreenLoading();
          }
          if (param.auth != false && store.getters.userInfo.token != null && store.getters.userInfo.token != undefined) {
            config.headers.Authorization =`Bearer ${JSON.parse(store.getters.userInfo.token).auth_token}`;
          }
          config.headers.timestamp = http.getRandomStr();
          return config;
        },
        (error) => {
          if (param.modal) {
            http.tryHideFullScreenLoading();
          }
          Message.error({ message: '请求超时!', type: "warning", offset: 400 ,showClose:true});
          return Promise.reject(error);
        }
      );
      // 回复拦截，主要针对部分回掉数据状态码进行处理
      serivce.interceptors.response.use(
        (response) => {
          if (param.modal) {
            http.tryHideFullScreenLoading();
          }
          if (response.data) {
            return response;
          } else {
            Message.error({ message: '接口错误!', type: "warning", offset: 400 ,showClose:true});
          }
        },
        (error) => {
          if (param.modal) {
            http.tryHideFullScreenLoading();
          }
          if (error.response.status === 401) {
            router.push({ path: "/" });
          }
          return Promise.reject(error);
        },
      );
      if (param.method == undefined || param.method == "POST") {
        return new Promise((resolve, reject) => {
          serivce({
            method: 'post',
            url: param.url,
            data: param.data
          }).then(res => {
            resolve(res)
          }).catch(err => {
            Message.error({ message: err || '错误', type: "warning", offset: 400 ,showClose:true});
            console.log(err, '异常');
          })
        })
      } else if (param.method == "GET") {

        if (param.data!=undefined&&param.data!=null) {
          Object.keys(param.data).forEach(function(key){
            if (param.url.indexOf('{'+key+'}')>-1) {
              param.url=param.url.replace('{'+key+'}',param.data[key]);
            } else {
              Message.error({ message: '请求地址中的参数未包含ajax传递的对象中的属性。请求地址为：'+param.url, type: "warning", offset: 400 ,showClose:true});
              console.log('请求地址中的参数未包含ajax传递的对象中的属性。请求地址为：'+param.url, '异常');
            }
          });
        }
        
        return new Promise((resolve, reject) => {
          serivce({
            method: 'get',
            url: param.url,
            params: param.data
          }).then(res => {
            resolve(res);
          }).catch(err => {
            Message.error({ message: err || '错误', type: "warning", offset: 400 ,showClose:true});
            console.log(err, '异常');
          })
        });
      } else {}
    }
  },
  //开启遮罩层
  showFullScreenLoading() {
    if (needLoadingRequestCount === 0) {
      this.startLoading()
    }
    needLoadingRequestCount++
  },
  startLoading() {
    loadingInstance = Loading.service({
      fullscreen: true,
      text: '拼命加载中...',
      background: 'rgba(0, 0, 0, 0.8)'
    })
  },
  //隐藏遮罩层
  tryHideFullScreenLoading() {
    if (needLoadingRequestCount <= 0) return
    needLoadingRequestCount--
    if (needLoadingRequestCount === 0) {
      this.endLoading()
    }
  },
  endLoading() {
    loadingInstance.close()
  },
  /**
   * 获取不重复UUID
   * @param {any} 
   */
  getRandomStr: function () {
    var s = [];
    var hexDigits = "0123456789abcdef";
    for (var i = 0; i < 36; i++) {
      s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = "4";
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
    s[8] = s[13] = s[18] = s[23] = "-";
    return s.join("");
  },
}
export default http
